package tt.dz.egobus.servicemanager.core.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.WebUtils;
import tt.dz.egobus.servicemanager.bean.UserSession;
import tt.dz.egobus.servicemanager.core.exception.SessionTimeoutException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Anson
 * @date 17-3-24
 * @name session 控制器 通过异常处理，抛出异常
 * @since 1.0.2
 */
public class SessionHandlerInterceptorAdapter extends SessionInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(SessionHandlerInterceptorAdapter.class);


    @Override
    protected boolean isFilter(HttpServletRequest request) {
        return true;
    }

    @Override
    protected boolean successSessionValidate(UserSession userSession, HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (userSession == null) {
            return false;
        }
        userSession.updateSession();
        WebUtils.setSessionAttribute(request, ADMIN_SESSION_KEY, userSession.toJson());
        return true;
    }

    @Override
    protected boolean invalidateSessionValidate(UserSession userSession, HttpServletRequest request, HttpServletResponse response, Object handler) {
        LOGGER.info("当前用户session超时,处理当前用户登陆session为null");
        WebUtils.setSessionAttribute(request, ADMIN_SESSION_KEY, null);
        throw new SessionTimeoutException("登陆超时");
    }
}
